<script lang="ts" setup>
import "@/utils/rem"
import { reactive, ref } from "vue"
import { useRouter } from "vue-router"
import { showToast } from "vant"
import { getComboDetails, getPhoneCode, createH5DataApi } from "@/api/stock-operation/stockOrderH5"
document.title = ""
// import { formatDateTime } from "@/utils"
const router = useRouter()
const pid = router.currentRoute.value.query.pid // 套餐id
// const sid = router.currentRoute.value.query.sid
const tid = router.currentRoute.value.query.tid

const showBottom = ref<boolean>(false)
const carderAd = ref<string>("")
const cascaderValue = ref<string>("")
const checked = ref(false) // 协议确认按钮
const showdialog = ref(false) // 协议弹出框
const showdialogCG = ref(true) // 领取成功弹出框
const agreement = ref("") // 协议内容
const formData = reactive<any>({
  data: {}
})
// const imgTopUrl = ref<string>("")
const productName = ref<string>("")
const imgDetailUrl = ref<string>("")
const imgVerify = ref<string>("") //二确图
const send = ref("获取验证码")
const codeTime = ref(false)
/**获取手机验证码 */
const time = ref(60)
const getCode = () => {
  // if (checked.value == false) return showToast("请先勾选用户协议！")
  const reg = /^1(3[4-9]|4[7]|5[012789]|7[28]|8[23478]|9[578])\d{8}$/ // 判断移动手机号
  if (formData.data.phone && reg.test(formData.data.phone)) {
    codeTime.value = true
    const timer = setInterval(() => {
      time.value--
      if (time.value >= 0) {
        send.value = time.value + "s后刷新"
      } else if (time.value < 0) {
        send.value = "获取验证码"
        codeTime.value = false
        clearInterval(timer)
        time.value = 60
      }
    }, 1000)
    formData.data.stockId = pid // 套餐id
    getPhoneCode(formData.data).then((res: any) => {
      console.log(res)
      formData.data.orderid = res.data
    })
  } else {
    showToast("请输入移动手机号！")
  }
}

/**获取产品详情 */
const successInfo = ref<any>("")
const getProduct = async () => {
  await getComboDetails(pid).then(async (res: any) => {
    console.log(res)
    if (res.code == 200) {
      imgDetailUrl.value = `${import.meta.env.VITE_BASE_API}/image/${res.data.imgBackground}`
      imgVerify.value = `${import.meta.env.VITE_BASE_API}/image/${res.data.imgVerify}`
      // imgTopUrl.value = `http://192.168.0.152:8080/image/${res.data.img}`
      // imgDetailUrl.value = `http://192.168.0.152:8080/image/${res.data.imgBackground}`
      productName.value = res.data.name
      document.title = res.data.name
      agreement.value = res.data.agreement
      successInfo.value = res.data.info
      await imgHeight(`${import.meta.env.VITE_BASE_API}/image/${res.data.imgBackground}`)
    }
  })
}
getProduct()
const isHeight = ref<any>()
const imgUrl = ref<any>()
const imgHeight = (url: any) => {
  return new Promise((resolve, reject) => {
    const imgObj = new Image()
    imgObj.src = url
    imgObj.onload = () => {
      imgUrl.value = url
      isHeight.value = imgObj.height / 100 + "rem"
    }
    // console.log(imgObj)
    reject("")
  })
}

const onSubmit = async (values: any) => {
  if (checked.value == false) return showToast("请先勾选用户协议！")
  console.log(values)
  // const PReg = /^1(3[4-9]|4[7]|5[012789]|7[28]|8[23478]|9[578])\d{8}$/
  // if (!formData.data.phone || !PReg.test(formData.data.phone)) {
  //   showToast(`请输入移动的手机号`)
  //   return
  // }
  /**下单逻辑 */
  if (!formData.data.note) {
    showToast("请填写验证码！")
    return false
  }
  formData.data.stockId = pid // 套餐id
  formData.data.tid = tid // 分享人id
  await createH5DataApi(formData.data)
    .then((res: any) => {
      if (res.code == 200) {
        // 清空reactive对象里面的key值
        formData.data = {}
        carderAd.value = ""
        cascaderValue.value = ""
        showToast("下单成功")
        showBottom.value = false
        // formData.data.takeAddress = ""
        checked.value = false // 协议勾选框
        showdialog.value = false // 领取成功之后的弹框
        showdialogCG.value = true // 领取成功之后的弹框
      }
    })
    .finally(() => {
      carderAd.value = ""
      cascaderValue.value = ""
    })
}
const canclePop = () => {
  showBottom.value = false
  checked.value = false // 协议勾选框
  showdialog.value = false // 领取成功之后的弹框
  formData.data.note = ""
}
// #region 用户协议
// function confirmFn() {
//   checked.value = true
// }
function YH() {
  showdialog.value = true
}
const showErQue = () => {
  const pattern = /^1(3[4-9]|4[7]|5[012789]|7[28]|8[23478]|9[578])\d{8}$/ // 判断移动手机号
  if (pattern.test(formData.data.phone)) {
    showBottom.value = true
  } else {
    showToast("手机号码不正确,请输入移动手机号码！")
    return
  }
}
// #endregion
</script>
<template>
  <div
    :style="`width: 7.5rem; height: ${isHeight}; margin: 0 auto; overflow-y: hidden;background:url(${imgUrl})no-repeat;background-size: 100%`"
  >
    <div class="view_bottom">
      <van-form>
        <van-cell-group inset>
          <van-field
            v-model="formData.data.phone"
            name="手机号"
            label="手机号"
            size="small"
            placeholder="请输入手机号(已加密)"
            maxlength="11"
          />
        </van-cell-group>
      </van-form>
      <van-button style="margin-top: 0.5rem" round icon="guide-o" type="primary" @click="showErQue"
        >立即订购</van-button
      >
    </div>
    <van-popup v-model:show="showBottom" closeable close-icon="close" position="bottom" :style="{ height: '100%' }">
      <div class="pop">
        <div style="margin-bottom: 0.2rem">
          <van-image width="100%" :src="imgVerify" />
        </div>
        <van-form @submit="onSubmit">
          <van-cell-group inset>
            <van-field
              v-model="formData.data.note"
              center
              clearable
              label="短信验证码"
              placeholder="请输入短信验证码"
              maxlength="4"
            >
              <template #button>
                <van-button size="small" type="primary" :disabled="codeTime" @click="getCode"> {{ send }}</van-button>
              </template>
            </van-field>
            <div style="display: flex; margin-top: 0.2rem; align-items: center">
              <van-checkbox v-model="checked" />
              <span style="margin-left: 0.2rem; font-size: 0.23rem; color: #1989fa" @click="YH">
                我已阅读并同意上述内容
              </span>
            </div>
          </van-cell-group>
          <div style="width: 100%; text-align: center">
            <van-button
              @click="canclePop"
              round
              block
              type="default"
              style="width: 40%; display: inline-block; margin-right: 5%"
            >
              我再想想
            </van-button>
            <van-button
              round
              block
              type="primary"
              style="width: 40%; display: inline-block; margin-left: 5%"
              native-type="submit"
            >
              立即订购
            </van-button>
          </div>
        </van-form>
      </div>
    </van-popup>
    <!-- 领取成功之后的弹框 -->
    <van-dialog width="7.5rem" v-model:show="showdialogCG" show-cancel-button>
      <div style="padding: 0.2rem">
        <div><img class="imgcg" src="../../assets/layout/lqcg.png" /></div>
        <div class="info-suc" style="background-color: #fff; padding: 0.1rem" v-html="successInfo" />
      </div>
    </van-dialog>
  </div>
</template>
<style lang="scss" scoped>
.bg {
  // height: 100%;
  // background: url("@/assets/layout/ordersearch.png") no-repeat;
  // background-size: 100% 100%;
  background-color: #fff;
  overflow-y: auto;
}
:deep(.van-image) {
  display: block !important;
}
.view1 {
  width: 7.5rem;
  margin: 0 auto;
}
h2 {
  font-size: 14px;
  font-weight: bold;
  padding: 8px 0;
}
.view_7 {
  font-weight: bold;
  font-size: 16px;
  position: relative;
  padding-left: 15px;
  margin: 25px 0;
}
.view_7::after {
  position: absolute;
  content: "";
  left: 0;
  top: 0;
  width: 3px;
  height: 16px;
  background: #1a54fa;
  border-radius: 2px;
}
.view_bottom {
  position: relative;
  left: 50%;
  top: 7.8rem;
  padding: 0.1rem 0;
  box-sizing: border-box;
  width: 7rem;
  margin-left: -3.5rem;
  box-sizing: initial;
  line-height: 0;
  :deep(.van-button) {
    width: 100%;
  }
}

.pop {
  .view_7::after {
    top: 8px;
  }
}
.title {
  font-size: 18px;
  font-weight: 700;
  text-align: center;
}

// 协议样式
.imgbox {
  height: 11rem;
}
.imgbg {
  position: absolute; /*设为绝对定位*/
  width: 100%; /* 或者其他固定宽度 */
  height: auto;
  object-fit: contain; /* 保持图片的宽高比 */
}
.imgtext {
  width: 75%;
  height: 60%;
  margin: 100px 0 0 45px;
  position: absolute; /*设为绝对定位*/
  overflow: scroll;
  scrollbar-width: none;
}
::-webkit-scrollbar {
  width: 12px; /* 设置滚动条的宽度 */
}
.imgcg {
  width: 100%; /* 或者其他固定宽度 */
  height: auto;
  object-fit: contain; /* 保持图片的宽高比 */
}
.info-suc p {
  margin: 0 !important;
}
</style>
